<!--
 * Copyright © 2025 上海火金网络科技有限公司. All rights reserved.
 * This is a custom detail page for article management.
 *
 * Website: https://www.miaoma.com
-->

<template>
  <a-drawer
    v-model:open="drawerVisible"
    width="70%"
    placement="right"
    title="文章详情"
    :closable="true"
    @close="closeDrawer"
  >
    <div class="article-detail">
      <a-card :bordered="false">
        <template #title>
          <div class="article-header">
            <h1>{{ article.title }}</h1>
            <div class="article-meta">
              <span class="author">作者：{{ article.author }}</span>
              <span class="time">创建时间：{{ formatDate(article.createdTime) }}</span>
              <a-tag :color="getStatusColor(article.status)">
                {{ getStatusText(article.status) }}
              </a-tag>
            </div>
          </div>
        </template>

        <div class="article-content">
          <div v-if="article.content" class="content-wrapper">
            <div v-html="formatContent(article.content)"></div>
          </div>
          <div v-else class="no-content">
            <a-empty description="暂无内容" />
          </div>
        </div>

        <template #actions>
          <a-space>
            <a-button @click="closeDrawer">
              <template #icon><arrow-left-outlined /></template>
              返回列表
            </a-button>
            <a-button type="primary" @click="handleEdit" v-if="isDraftStatus">
              <template #icon><edit-outlined /></template>
              编辑
            </a-button>
            <a-button @click="handleDownload">
              <template #icon><download-outlined /></template>
              下载
            </a-button>
          </a-space>
        </template>
      </a-card>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import { ArrowLeftOutlined, EditOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import { apiDownloadArticle } from './api'
import type { MiaomaArticle } from './types'

interface ArticleItem {
  id: number
  title: string
  author: string
  content: string
  status: string
  createdTime: string
  updatedTime?: string
}

const drawerVisible = ref(false)
const article = ref<ArticleItem>({
  id: 0,
  title: '',
  author: '',
  content: '',
  status: '2',
  createdTime: ''
})

const emit = defineEmits(['edit'])

// 计算属性：判断是否为草稿状态
const isDraftStatus = computed(() => {
  const status = String(article.value.status).toLowerCase()
  return status === '2' || status === 'draft'
})

const getStatusText = (status: string | number): string => {
  const statusStr = String(status).toLowerCase()
  const statusMap: Record<string, string> = {
    '1': '已发布',
    '2': '草稿',
    '0': '已下线',
    'published': '已发布',
    'draft': '草稿',
    'offline': '已下线'
  }
  return statusMap[statusStr] || `未知状态(${status})`
}

const getStatusColor = (status: string | number): string => {
  const statusStr = String(status).toLowerCase()
  switch (statusStr) {
    case '1':
    case 'published':
      return 'green'
    case '2':
    case 'draft':
      return 'orange'
    case '0':
    case 'offline':
      return 'red'
    default:
      return 'default'
  }
}

const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatContent = (content: string) => {
  if (!content) return ''
  // 优化的 Markdown 转 HTML 处理
  return content
    .replace(/\r\n/g, '\n')
    .replace(/\n/g, '<br>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`([^`]+)`/g, '<code>$1</code>')
    .replace(/^### (.+)$/gm, '<h3>$1</h3>')
    .replace(/^## (.+)$/gm, '<h2>$1</h2>')
    .replace(/^# (.+)$/gm, '<h1>$1</h1>')
}

const openDrawer = (item: MiaomaArticle) => {
  article.value = {
    ...item,
    createdTime: item.createdTime || '',
    updatedTime: item.updatedTime || ''
  }
  drawerVisible.value = true
}

const closeDrawer = () => {
  drawerVisible.value = false
  article.value = {
    id: 0,
    title: '',
    author: '',
    content: '',
    status: '2',
    createdTime: ''
  }
}

const handleEdit = () => {
  emit('edit', article.value)
  closeDrawer()
}

const handleDownload = async () => {
  try {
    await apiDownloadArticle(article.value.id)
    message.success('文章下载成功')
  } catch (error) {
    console.error('下载文章失败:', error)
    message.error('下载文章失败')
  }
}

defineExpose({ openDrawer })
</script>

<style scoped>
.article-detail {
  height: 100%;
}

.article-header {
  margin-bottom: 24px;
}

.article-header h1 {
  margin-bottom: 16px;
  font-size: 24px;
  font-weight: 500;
}

.article-meta {
  color: rgba(0, 0, 0, 0.45);
}

.article-meta span {
  margin-right: 16px;
}

.article-content {
  margin: 24px 0;
  line-height: 1.8;
  min-height: 200px;
}

.content-wrapper {
  white-space: pre-wrap;
  word-break: break-word;
}

.content-wrapper :deep(h1),
.content-wrapper :deep(h2),
.content-wrapper :deep(h3) {
  margin: 16px 0 8px 0;
  font-weight: 600;
}

.content-wrapper :deep(h1) {
  font-size: 20px;
}

.content-wrapper :deep(h2) {
  font-size: 18px;
}

.content-wrapper :deep(h3) {
  font-size: 16px;
}

.content-wrapper :deep(strong) {
  font-weight: 600;
}

.content-wrapper :deep(em) {
  font-style: italic;
}

.content-wrapper :deep(code) {
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: monospace;
  font-size: 14px;
  color: #d63384;
}

.no-content {
  text-align: center;
  padding: 60px 0;
  color: rgba(0, 0, 0, 0.45);
}
</style>